package com.devcon5.StudentPlanner;

import java.util.Calendar;
import baseclasses.Assignment;
import baseclasses.Course;
import baseclasses.Reminder;
import database.AssignmentDAO;
import database.ReminderDAO;
import forms.AssignmentForm;

import android.app.AlarmManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class EditAssignment extends AssignmentForm{

	private Assignment assignment;
	private Reminder reminder = null;
	private boolean selected = false;
	public static String ADD_REMINDER = "addreminder";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//	set assignment ID = assignment ID retrieved from intent extras passed from 
		int assignmentId = getIntent().getExtras().getInt( Assignment.ASSIGNMENT_ID );
		assignment = AssignmentDAO.getAssignmentById(context, assignmentId);



		
		// Unpack the AssignmentView intent extras if accessed from assignmentview class
		boolean popUpReminder = getIntent().getExtras().getBoolean(ADD_REMINDER);

		addButton.setText("Save");

		//If there is a saved instance state (orientation changed)

		if(savedInstanceState != null)
		{
			timeChanged = savedInstanceState.getBoolean(TIME_CHANGED);
			dueDateLong = savedInstanceState.getLong(DUE_DATE_LONG);
			dueDate = Calendar.getInstance();
			dueDate.setTimeInMillis(dueDateLong);
			dueDateText.setText(Assignment.getDueDateString(dueDate, "MM/dd/yyyy"));
			timeDueText.setText(Course.getStartTimeString(dueDate, "hh:mm a"));
			
			remindInteger = savedInstanceState.getInt(REMINDER_INT);
			remindString = savedInstanceState.getString(REMINDER_STRING);
			updateReminderTextView();
		}
		else
		{
			//set all form widgets to assignment details
			assignmentName.setText(assignment.getName());
			description.setText(assignment.getDescription());
			dueDate = assignment.getDueDate();
			dueDateText.setText(assignment.getDueDateString("MM/dd/yyyy"));
			timeDueText.setText(assignment.getDueDateString("hh:mm a"));
			courseSpinner.setSelection(getCoursePositionByAssignmentId());

			//if reminder is not null, get reminder
			reminder = ReminderDAO.getReminderByAssignment(context, assignment);
			if(reminder!=null)
			{
				reminderToggleButton.setChecked(true);
				remindInteger = reminder.getInteger();
				remindString = reminder.getUnits();
				updateReminderTextView();	//update the display
			}

			if (popUpReminder == true){	//if accessed from the assignmentview class, immediately display the reminder layout
				reminderLayout.performClick();
			}
		}



		//change due date time according to the selected course start time
		courseSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(!timeChanged)
				{
					if(selected)
					{
						dueDate.set(Calendar.HOUR_OF_DAY, courses.get(arg2).getStartTime().get(Calendar.HOUR_OF_DAY));
						dueDate.set(Calendar.MINUTE, courses.get(arg2).getStartTime().get(Calendar.MINUTE));
						timeDueText.setText(assignment.getDueDateString("hh:mm a"));
					}
					else
						selected = true;
				}
				courseID = courses.get(arg2).getId();
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}




	//returns the position of the course in the course spinner
	public int getCoursePositionByAssignmentId(){

		for(int i=0; i < courses.size(); i++){
			if( courses.get(i).getId() == assignment.getCourseId()){
				return i;
			}
		}
		return -1;
	}





	@Override
	protected void onSaveButtonClicked() {

		//Save the information to the variables for this Assignment
		assignment.setName(assignmentNameString);
		assignment.setDescription(descriptionString);
		assignment.setDueDate(dueDate);
		assignment.setCourseId(courseID);

		long assignmentId = AssignmentDAO.editAssignment(context, assignment);	//get the id as a result of editing the assignment data
																				//associated with this assignment, as well as this context
		if(assignmentId == -1){	//If it's still a default flag, 
			Toast.makeText(context, "Error editing assignment", Toast.LENGTH_SHORT).show();
		}
		else{
			if(reminderToggleButton.isChecked()){

				if(reminder == null){ //If there's no reminder yet
					reminder = new Reminder(assignment.getId(), remindInteger, remindString);	//Get reminder int and string and assign it to this assignment ID
					if(ReminderDAO.addReminder(context, reminder)!=-1){	//If the reminder was registered in the database
						AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);	//get the alarm manager service
						reminder.createAlarm(context, dueDate, am);		//create and register alarm between alarmManager and broadcast receiver
					}
				}
				else{
					reminder.setInteger(remindInteger);	//Set reminder integer and units (days, hours, minutes) to the reminder variable
					reminder.setUnits(remindString);
					if(ReminderDAO.editReminder(context, reminder)!=-1){	//If the reminder is successfully edited, create and register w/ alarmManager
						AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
						reminder.createAlarm(context, dueDate, am);
					}
				}
				
			}
			else{	//if the reminderToggleButton isn't checked
				if(reminder!=null){	//If there is a reminder for that assignment
					AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);	
					reminder.cancelAlarm(context, dueDate, am);	//unregister that alarm with the alarmManager
					ReminderDAO.deleteReminder(context, reminder);	//delete the reminder from the database
				}
			}
		}

	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {	//persisting data on orientation change or activity pushed back

		outState.putLong(DUE_DATE_LONG, dueDate.getTimeInMillis());
		outState.putInt(REMINDER_INT, remindInteger);
		outState.putString(REMINDER_STRING, remindString);
		outState.putBoolean(TIME_CHANGED, timeChanged);
		
		super.onSaveInstanceState(outState);
	}

}

